// pages/bind/bind.js
Page({
  data: {
    deviceId: "",
    secret: "",
    errorMsg: "",
    isLoading: false,
  },

  onLoad(options) {
    // 页面加载时执行的逻辑
  },

  onDeviceIdInput(e) {
    this.setData({
      deviceId: e.detail.value,
      errorMsg: "",
    });
  },

  onSecretInput(e) {
    this.setData({
      secret: e.detail.value,
      errorMsg: "",
    });
  },

  // 处理绑定请求
  handleBind() {
    const { deviceId, secret } = this.data;

    // 表单验证
    if (!deviceId.trim()) {
      this.setData({ errorMsg: "请输入设备ID" });
      return;
    }

    if (!secret) {
      this.setData({ errorMsg: "请输入设备密钥" });
      return;
    }

    // 显示加载状态
    this.setData({ isLoading: true });

    // 获取用户ID
    const userInfo = wx.getStorageSync("userInfo");
    const userId = userInfo ? userInfo.userId : null;

    if (!userId) {
      this.setData({
        errorMsg: "用户信息获取失败，请重新登录",
        isLoading: false,
      });
      return;
    }

    // 生成时间戳
    const timestamp = Date.now();

    // 发送绑定请求
    const app = getApp();
    wx.request({
      url: `${app.globalData.deviceApiBaseUrl}/api/v1/bind`,
      method: "POST",
      data: {
        device_id: deviceId,
        secret: secret,
        user_id: userId,
        timestamp: timestamp,
      },
      success: (res) => {
        if (res.data && res.data.code === 0) {
          // 绑定成功，保存设备信息到本地缓存
          wx.setStorageSync("deviceInfo", {
            deviceId: deviceId,
            deviceKey: secret
          });
          
          console.log("设备绑定成功，已更新缓存:", deviceId);
          
          wx.showToast({
            title: "设备绑定成功",
            icon: "success",
            duration: 2000,
            success: () => {
              // 延迟返回主页
              setTimeout(() => {
                wx.navigateBack();
              }, 2000);
            },
          });
        } else {
          // 绑定失败，显示错误信息
          let errorMessage = "设备绑定失败";
          if (res.data && res.data.message) {
            errorMessage = res.data.message;
          }
          this.setData({
            errorMsg: errorMessage,
            isLoading: false,
          });
        }
      },
      fail: (err) => {
        console.error("绑定请求失败", err);
        this.setData({
          errorMsg: "网络错误，请稍后重试",
          isLoading: false,
        });
      },
    });
  },
});
